package com.heima.controller.vm_service;

import com.heima.pojo.entity.Region;
import com.heima.pojo.dto.RegionDto;
import com.heima.pojo.vo.PageVo;
import com.heima.service.RegionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/vm-service")
@Slf4j
public class RegionController {

    @Autowired
    private RegionService regionService;

    /**
     * 区域分页查询
     */
    @GetMapping("/region/search")
    public PageVo pageRegion(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                             @RequestParam(value = "pageSize", required = false) Integer pageSize,
                             @RequestParam(value = "name", required = false) String name) {
        PageVo pageVo = regionService.getPage(pageIndex, pageSize, name);
        return pageVo;
    }

    /**
     * 新增区域
     */
    @PostMapping("/region")
    public Boolean save(@RequestBody RegionDto regionDto) {
        log.info("区域新增参数： {}", regionDto);
        Boolean result = regionService.save(regionDto);
        return result;
    }

    /**
     * 修改区域
     */
    @PutMapping("/region/{regionId}")
    public Boolean update(@PathVariable String regionId, @RequestBody Region region) {
        log.info("区域修改参数： {}", region);
        // 清理所有可能的非法值
        cleanRegionData(region);

        Boolean result = regionService.update(regionId, region);
        return result;
    }

    /**
     * 清理 Region 对象中的非法值
     *
     * @param region
     */
    private void cleanRegionData(Region region) {
        // 清理字符串字段
        if (region.getName() != null && ("undefined".equals(region.getName()) || "null".equals(region.getName()))) {
            region.setName(null);
        }

        if (region.getRemark() != null && ("undefined".equals(region.getRemark()) || "null".equals(region.getRemark()))) {
            region.setRemark(null);
        }

    }

//    /**
//     * 查看区域详情
//     */
//    @GetMapping("/node/search")
//    public RegionNodePageVo getRegionById(@RequestParam Integer pageIndex, Integer pageSize, String regionId){
//        RegionNodePageVo regionNodePageVo = regionService.getById(pageIndex,pageSize,regionId);
//        return regionNodePageVo;
//    }
    /**
     * 删除区域
     */
    @DeleteMapping("/region/{regionId}")
    public Boolean delete(@PathVariable  Long regionId){
      return   regionService.delete(regionId);
    }
}


















